import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'

class MathEditor extends BaseFloat {
  static pluginName = 'mathEditor'

  constructor (muya) {
    const name = 'ag-math-editor'
    super(muya, name)
    this.oldVnode = null
    this.mathContainer = document.createElement('div')
    this.container.appendChild(this.mathContainer)
    this.listen()
  }

  listen () {
    const { eventCenter } = this.muya
    super.listen()

    // 监听数学公式输入
    this.muya.on('change', ({ markdown, cursor, wordCount, history, toc }) => {
      console.log('1change', markdown, cursor, wordCount, history, toc)
      if (!cursor || !cursor.start) return
      console.log('2change', cursor)
      const { start } = cursor
      const block = this.muya.contentState?.getBlock(start.key)
      if (block && block.text) {
        const text = block.text
        if (text.endsWith('$')) {
          const type = text.endsWith('$$') ? 'block' : 'inline'
          eventCenter.emit('muya-math-editor', {
            type,
            cursor: start
          })
        }
      }
    })

    // 统一使用 eventCenter 监听
    eventCenter.subscribe('muya-math-editor', (data, reference, cb) => {
      if (!this.status) {
        this.show(data, reference, cb)
        this.render()
      } else {
        this.hide()
      }
    })
  }

  render () {
    const { oldVnode, mathContainer } = this
    const vnode = h('div.ag-math-editor', [
      h('div.math-editor-container', {
        props: {
          contenteditable: true
        }
      })
    ])

    if (oldVnode) {
      patch(oldVnode, vnode)
    } else {
      patch(mathContainer, vnode)
    }
    this.oldVnode = vnode
  }

  show (data, reference, cb) {
    this.data = data
    super.show(reference, cb)
  }

  hide () {
    super.hide()
  }
}

export default MathEditor